package com.spring.test.controller;

import com.spring.test.domain.Role;
import com.spring.test.domain.User;
import com.spring.test.service.RoleService;
import com.spring.test.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Resource
    private UserService service;

    @Resource
    private RoleService roleService;

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){

        User user = service.login(username,password);

        if ( user != null ){
            //登录成功 放行
            session.setAttribute("user",user);

            return "redirect:/index.jsp";
        }

        return "redirect:/login.jsp";
    }

    @RequestMapping("/del/{userId}")
    public String del(@PathVariable("userId") Long userId){

        service.del(userId);

        return "redirect:/user/list";
    }

    @RequestMapping("/save")
    public String save(User user,Long[] roleIds){

        service.save(user,roleIds);

        return "redirect:/user/list";
    }


    @RequestMapping("/saveUI")
    public ModelAndView saveUI(){

        ModelAndView model = new ModelAndView();

        List<Role> roleList = roleService.list();

        model.addObject("roleList",roleList);

        model.setViewName("user-add");

        return model;
    }


    @RequestMapping("/list")
    public ModelAndView list(){

        List<User> userList = service.list();

        ModelAndView model = new ModelAndView();

        model.addObject("userList",userList);

        model.setViewName("user-list");

        return model;
    }


}
